package qingke.chat;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import qingke.pojo.Information;

/**
 * Servlet implementation class SendChatServlet
 */
@WebServlet("/SendChatServlet")
public class SendChatServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SendChatServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setCharacterEncoding("UTF-8");
		List<Information> ins = (List<Information>) request.getServletContext().getAttribute("information");
//		List<String> msgs = (List<String>)request.getServletContext().getAttribute("chat");
		if(ins == null){
			ins = new ArrayList<Information>();
		}
		String username = null;
		Cookie[] cookies = request.getCookies();
		if(cookies!=null){
			username = cookies[0].getValue();
		}
		String msg = request.getParameter("message");
		Date date=new Date();
		DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time=format.format(date);
		Information in = new Information();
		in.setTime(time);
		in.setMessage(msg);
		in.setUsername(username);
		if(in.getMessage() != null && !in.getMessage().trim().equals("")){
			ins.add(in);
		}
		request.getSession().setAttribute("time", time);
		request.getServletContext().setAttribute("information", ins);
		response.getWriter().append("Send ");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
